package com.gexiaobao.pigeon.ui.pigeoncatcher

import android.annotation.SuppressLint
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Paint
import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.model.bean.CarListBean
import com.gexiaobao.pigeon.app.model.bean.OrderDrippingDetailResponse
import com.gexiaobao.pigeon.app.util.ImageLoaderManager
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.ActivityDriveringOrderDetailBinding
import com.gexiaobao.pigeon.permissions.PermissionInterceptor
import com.gexiaobao.pigeon.ui.adapter.DrippingOrderDetailPigeonListAdapter
import com.gexiaobao.pigeon.ui.dialog.RxDialogCarList
import com.gexiaobao.pigeon.ui.dialog.RxDialogDefault
import com.gexiaobao.pigeon.ui.dialog.RxDialogSingle
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityAddCarInfo
import com.gexiaobao.pigeon.viewmodel.PigeonCatcherViewModel
import com.google.gson.Gson
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody


/**
 * @Author      : hxw
 * @Date        : 2024/6/28 16:13
 * @Describe    : 接单详情（司机）
 */
class ActivityDrippingOrderDetail : BaseActivity<PigeonCatcherViewModel, ActivityDriveringOrderDetailBinding>() {

    private var mOrderId = ""
    private var mTransporterId = ""
    private var orgName = ""
    private var userPhone = ""
    private var shedPhone = ""
    private var contactName = ""
    private var address = ""
    private var userSignUrl = ""
    private var catcherSignUrl = ""
    private var orgSignUrl = ""
    private var mLatitude: Double = 0.0
    private var mLongitude: Double = 0.0
    private var driverLat: Double = 0.0
    private var driverLng: Double = 0.0
    private var mStatus = 0
    private var mCarId = 0
    private var mOrgId = 0
    private val mAdapter: DrippingOrderDetailPigeonListAdapter by lazy { DrippingOrderDetailPigeonListAdapter(arrayListOf()) }

    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mDatabind.tvOrderDetailPhoneNumber.paint.flags = Paint.UNDERLINE_TEXT_FLAG
        mTransporterId = KvUtils.decodeString(Constant.USERID)
        mOrderId = intent.getIntExtra("id", 0).toString()
        orgName = intent.getStringExtra("orgName").toString()
        driverLat = intent.getDoubleExtra("driverLat", 0.0)
        driverLng = intent.getDoubleExtra("driverLng", 0.0)

        mDatabind.tvOrderDetailOrgName.text = orgName + "交鸽单"

        onRefresh()
        mDatabind.swipeRecyclerView.init(LinearLayoutManager(this), mAdapter).addItemDecoration(
            SpaceItemDecoration(0, 0)
        )

        mDatabind.swipeRefreshLayout.init {
            onRefresh()
        }

        eventViewModel.toRefreshDataStr.observeInActivity(this) {
            if (it == "ActivityDovetailSign") {
                onRefresh()
            }
        }
    }

    fun onRefresh() {
        showLoading(getString(R.string.loading))
        mViewModel.getOrderDidiDetail(mOrderId)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        /** 订单（订单状态变更）(接鸽员)  */
        mViewModel.returnOrderResult.observe(this) {
            eventViewModel.toRefreshDataStr.value = "ActivityDrippingOrderDetail"
            onRefresh()
        }
        /** 接订单/指定订单接收（订单状态变更）  */
        mViewModel.receiveOrderResult.observe(this) {
            eventViewModel.toRefreshDataStr.value = "ActivityDrippingOrderDetail"
            onRefresh()
        }
        /** 获取订单详情 */
        mViewModel.drippingOrderDetailResult.observe(this) {
            if (mDatabind.swipeRefreshLayout.isRefreshing) {
                mDatabind.swipeRefreshLayout.isRefreshing = false
            }
            if (it != null) {
                mDatabind.data = it
                refreshDataUi(it)
            }
        }
        /** 查询接鸽员申请中关于汽车的信息列表  */
        mViewModel.carInfoListResult.observe(this) {
            if (it != null && it.list.isNotEmpty()) {
                if (it.list.size == 1) {
                    showSureReceipt(it.list[0].id)
                } else {
                    showCarListDialog(it.list)
                }
            } else {
                showSingleDialog()
            }
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.tvChargeBack,
            mDatabind.includeBar.ivBack,
            mDatabind.tvOrderDetailPhoneNumber,
            mDatabind.includeBtn.tvLeftBtn,
            mDatabind.includeBtn.tvRightBtn,
            mDatabind.ivUserSignImage,
            mDatabind.ivCatcherSignImage,
            mDatabind.ivShedSignImage
        ) {
            when (it) {
                mDatabind.ivUserSignImage ->
                    if (userSignUrl.isNotEmpty()) {
                        openBigImage(mDatabind.ivUserSignImage, userSignUrl)
                    }

                mDatabind.ivCatcherSignImage ->
                    if (catcherSignUrl.isNotEmpty()) {
                        openBigImage(mDatabind.ivCatcherSignImage, catcherSignUrl)
                    }

                mDatabind.ivShedSignImage ->
                    if (orgSignUrl.isNotEmpty()) {
                        openBigImage(mDatabind.ivShedSignImage, orgSignUrl)
                    }

                mDatabind.includeBtn.tvRightBtn -> {
                    startActivity<ActivityOrderRoutePlanning>(
                        "lat" to mLatitude,
                        "lon" to mLongitude,
                        "address" to address,
                        "driverLat" to driverLat,
                        "driverLng" to driverLng,
                        "phone" to userPhone,
                        "name" to contactName
                    )
                }

                mDatabind.tvChargeBack -> {
                    showChargeBackDialog()
                }

                mDatabind.includeBtn.tvLeftBtn -> {
                    when (mStatus) {
                        2 -> {
                            showLoading(getString(R.string.loading))
                            mViewModel.getTransporterApplyCarList()
                        }

                        3, 4 -> {
                            startActivity<ActivityDovetailSign>(
                                "phone" to userPhone,
                                "shedPhone" to shedPhone,
                                "orderId" to mOrderId,
                                "status" to mStatus
                            )
                        }

                        5 -> {
                            RxToast.showToast("查看签字")
                        }
                    }
                }

                mDatabind.tvOrderDetailPhoneNumber -> {
                    showDeleteDialog(mDatabind.tvOrderDetailPhoneNumber.text.toString())
                }

                mDatabind.includeBar.ivBack -> {
                    finish()
                }
            }
        }
    }

    private fun showCarListDialog(list: ArrayList<CarListBean>) {
        val dialog = RxDialogCarList(this)
        dialog.setList(list)
        dialog.setOnCarPassedListener(object : RxDialogCarList.OnClickCarListener {
            override fun onCarPassed(carId: Int) {
                mCarId = carId
            }
        })
        dialog.setCancelListener {
            mCarId = 0
            dialog.dismiss()
        }
        dialog.setSureListener {
            if (mCarId == 0) {
                RxToast.warning("请选择接单车辆")
                return@setSureListener
            }
            receiptOrder(mCarId)
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun showChargeBackDialog() {
        val dialog = RxDialogDefault(this)
        dialog.setContent("当天内最多可操作3次退单，超出则不可再次进行接单，请谨慎操作！")
        dialog.setLeftBtnContent("再想想")
        dialog.setRightBtnContent("确认撤单")
        dialog.setSureListener {
            val map = mapOf(
                "id" to mOrderId.toInt()
            )
            val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
            showLoading(getString(R.string.loading))
            mViewModel.returnOrderDidi(body)
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun showSureReceipt(carId: Int) {
        val dialog = RxDialogDefault(this)
        dialog.setContent("是否确认接单?接单后不可随意退单")
        dialog.setSureListener {
            receiptOrder(carId)
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun receiptOrder(carId: Int) {
        showLoading(getString(R.string.loading))
        val map = mapOf(
            "id" to mOrderId.toInt(),
            "transporterCarId" to carId,
            "transporterId" to mTransporterId.toInt(),
            "lon" to mLongitude,
            "lat" to mLatitude
        )
        val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
        mViewModel.receiveOrderDidi(body)
    }

    private fun showSingleDialog() {
        val dialog = RxDialogSingle(this)
        dialog.setTitle("暂无车辆，请添加车辆后再进行接单")
        dialog.setSureText("添加车辆")
        dialog.setSureListener {
            startActivity<ActivityAddCarInfo>("orgId" to mOrgId, "type" to "ActivityOrderSquare")
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun showDeleteDialog(phone: String) {
        val dialog = RxDialogDefault(this)
        dialog.setTitle("确定向以下手机号拨打电话？")
        dialog.setContent(phone)
        dialog.setSureListener {
            requestCallPermission()
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

    private fun requestCallPermission() {
        // 检查是否已授予相机权限
        if (XXPermissions.isGranted(this, Permission.CALL_PHONE)) {
            // 已经授予了相机权限 执行需要相机权限的操作
            val intent = Intent(Intent.ACTION_CALL)
            val data = Uri.parse("tel:$userPhone")
            intent.setData(data)
            startActivity(intent)
        } else {
            // 请求相机权限
            AlertDialog.Builder(this)
                .setTitle("请求拨打电话权限")
                .setMessage("App需要拨打电话权限，以便您能够直接拨打对方电话。")
                .setPositiveButton("确定") { dialog, which -> requestPermission() }
                .setNegativeButton("取消") { dialog, _ ->
                    // 用户取消了权限请求，可以进行相应处理
                    dialog.dismiss()
                }
                .show()
        }

    }

    private fun requestPermission() {
        XXPermissions.with(this)
            .permission(Permission.CALL_PHONE)
            .interceptor(PermissionInterceptor())
            .request { _, allGranted ->
                if (allGranted) {
                    val intent = Intent(Intent.ACTION_CALL)
                    val data = Uri.parse("tel:$userPhone")
                    intent.setData(data)
                    startActivity(intent)
                } else {
                    RxToast.showToast("权限不足，请手动开启权限后重试")
                }
            }
    }

    @SuppressLint("NotifyDataSetChanged", "SetTextI18n")
    private fun refreshDataUi(it: OrderDrippingDetailResponse) {
        userPhone = it.contactMobile
        shedPhone = it.orgMobile
        contactName = it.contactName
        mLatitude = it.lat
        mLongitude = it.lon
        address = it.address
        mStatus = it.status
        mOrgId = it.orgId
        userSignUrl = it.signUserPicUrl
        catcherSignUrl = it.signTransporterPicUrl
        orgSignUrl = it.signOrgPicUrl
        ImageLoaderManager.loadImage(this, userSignUrl, mDatabind.ivUserSignImage)
        ImageLoaderManager.loadImage(this, catcherSignUrl, mDatabind.ivCatcherSignImage)
        ImageLoaderManager.loadImage(this, orgSignUrl, mDatabind.ivShedSignImage)
        mDatabind.llSign.isVisible = mStatus > 3
        if (it.list != null && it.list.pigeons.isNotEmpty()) {
            mAdapter.setList(it.list.pigeons)
            mAdapter.notifyDataSetChanged()
        }
        mDatabind.tvDrippingOrderDetailPigeonCount.text = "赛鸽: " + it.list?.pigeons?.size.toString() + "羽"
        if (userPhone.isNotEmpty() && userPhone.length >= 11) {
            val result1 = userPhone.substring(0, 3)
            val result2 = userPhone.substring(7, userPhone.length)
            mDatabind.tvOrderDetailPhoneNumber.text = "$result1****$result2"
        }
        var title = ""
        var btnRightContent = ""
        var btnLeftContent = ""
        var isVisibleRight = false
        var isVisibleBack = false
        when (mStatus) {//1创建2发布3已接单4已接鸽5已完成
            2 -> {
                title = "待接单"
                btnLeftContent = "确认接单"
                isVisibleRight = false
                isVisibleBack = false
            }

            3 -> {
                title = "已接单"
                btnRightContent = "去接鸽"
                btnLeftContent = "用户签字"
                isVisibleBack = true
                isVisibleRight = true
            }

            4 -> {
                title = "已接鸽"
                btnLeftContent = "公棚签字"
                isVisibleBack = false
                isVisibleRight = false
            }

            5 -> {
                title = "已完成"
                isVisibleBack = false
                isVisibleRight = false
                btnLeftContent = "查看签字"
                mDatabind.includeBtn.llBottomBtn.isVisible = false
            }

            else -> {
                title = ""
                isVisibleBack = false
            }
        }
        mDatabind.includeBtn.tvRightBtn.text = btnRightContent
        mDatabind.includeBtn.tvLeftBtn.text = btnLeftContent
        mDatabind.includeBar.tvTitle.text = title
        mDatabind.tvChargeBack.isVisible = isVisibleBack
        mDatabind.includeBtn.tvRightBtn.isVisible = isVisibleRight
    }

}